package dataStructure;

/**
 * @author WuYongheng
 * @date 2022/3/27
 * @description Java中的链表是双向链表
 */
public class SingleLinkedList implements List {
    private Node head = new Node();// 头节点，不存储数据，为了编程方便
    private int size;// 一共有几个节点

    @Override
    public int size() {

        return size;
    }

    @Override
    public Object get(int i) {
        Node p = head;
        for (int j = 0; j <= i; j++) {
            p = p.next;
        }
        return p.data;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean contains(Object e) {
        return false;
    }

    @Override
    public int indexOf(Object e) {
        return 0;
    }

    @Override
    public void add(int i, Object e) {
        // 异常处理
        if(i<0||i>size){
            throw new MyArrayIndexOutOfBoundsException("数据指针越界异常"+i);
        }
        // 找到前一个节点，从head开始
        Node p = head;
        for (int j = 0; j < i; j++) {
            p = p.next;
        }
        Node newNode = new Node(e);
        newNode.data = e;
        // 新节点的前驱节点
        newNode.next = p.next;
        // 新节点的后继节点
        p.next = newNode;
        size++;
    }

    @Override
    public void add(Object e) {
        this.add(size, e);
    }

    @Override
    public boolean addBefore(Object obj, Object e) {
        return false;
    }

    @Override
    public boolean addAfter(Object obj, Object e) {
        return false;
    }

    @Override
    public Object remove(int i) {
        return null;
    }

    @Override
    public boolean remove(Object e) {
        return false;
    }

    @Override
    public Object replace(int i, Object e) {
        return null;
    }

    @Override
    public String toString() {
        if (size == 0) {
            return "[]";
        }
        StringBuilder sb = new StringBuilder("[");
        // p应该指向真正的第一个的节点，而不是head节点，所以是head.next
        Node p = head.next;
        for (int i = 0; i < size; i++) {
            if (i != size - 1) {
                sb.append(p.data + ",");
            } else {
                sb.append(p.data);
            }
            // p指向下一个节点
            p = p.next;
        }
        sb.append("]");
        return sb.toString();
    }
}
